package com.yl.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yl.auth.entity.Fangjian;
import com.yl.auth.entity.Shenpiliu;
import com.yl.auth.entity.Wcshenqing;
import com.yl.auth.entity.*;
import com.yl.auth.model.entity.*;
import com.yl.auth.model.vo.WcshenqingVo;
import com.yl.auth.service.*;
import com.yl.common.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.activiti.engine.*;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 李洁
 * @datetime 2023/7/7 14:06
 * @description 类对象
 */
@RestController
@RequestMapping("/admin/yanglao/shenpigaunli")
@Api(tags = "审批管理")
public class ShenPiGuanLiController {
    @Resource
    private LaorenService laorenService;
    @Resource
    private FangjianService fangjianService;
    @Resource
    private ChuangweiService chuangweiService;
    @Resource
    private CwgenghuanService cwgenghuanService;
    @Resource
    private WcshenqingService wcshenqingService;
    @Resource
    private ShenpiliuService shenpiliuService;
    @Resource
    private HuligenghuanshenpiService huligenghuanshenpiService;
    @Resource
    private HuLiDengJiBianGengService huLiDengJiBianGengService;
    @Resource
    private HulidengjiService hulidengjiService;
    @Resource
    private YuangongService yuangongService;
    @Resource
    private WaichushenqingshenpiService waichushenqingshenpiService;
    @ApiOperation("床位更换申请审批详情")
    @GetMapping("/getChuangWeiById/{id}")
    public Result getChuangWeiById(@PathVariable Integer id){
        //根据id获取护理变更信息
        Cwgenghuan cwgenghuan = cwgenghuanService.getById(id);
        //根据护理变更实体类中的老人外键获取到该老人信息
        Integer lrId = cwgenghuan.getLrId();
        Laoren laoren = laorenService.getById(lrId);
        //根据老人中的床位外键获取到该老人的床位信息
        Chuangwei chuangwei = chuangweiService.getById(laoren.getBedId());
        //根据老人中的房间外键获取到该老人指定的房间信息
        Fangjian fangjian = fangjianService.getById(laoren.getRoomId());
        //对获取到的房间号进行分割,循环取到房间号的第一个值
        String[] split = fangjian.getRoomNo().toString().split("");
        String str = "";
        for (int i = 0; i < split.length; i++) {
            str = split[0];
        }
        //获取到该老人房间信息
        laoren.setChuangWeiFangJian(str+"楼"+fangjian.getRoomNo()+"室");
        //获取到该老人床位信息
        laoren.setChuangWeiBed(fangjian.getRoomNo()+"/"+chuangwei.getBedNo());
        //获取到要更换的床位信息
        Chuangwei chuangwei1 = chuangweiService.getById(cwgenghuan.getCwsId());
        Fangjian fangjian1 = fangjianService.getById(cwgenghuan.getFjsId());
        cwgenghuan.setChuangWeiBed(fangjian1.getRoomNo()+"/"+chuangwei1.getBedNo());
        LambdaQueryWrapper<Yuangong> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Yuangong::getLaorenId,lrId);
        wrapper.groupBy(Yuangong::getLaorenId);
        Yuangong yuangong = yuangongService.getOne(wrapper);
        Map<String,Object> map = new HashMap<>();
        map.put("cwgenghuan",cwgenghuan);
        map.put("laoren",laoren);
        map.put("yuangong",yuangong);
        return Result.ok(map);
    }

    @ApiOperation("外出申请审批-全查+分页查+条件查询")
    @GetMapping("findAllWaiChu/{page}/{limit}")
    public Result findAllWaiChu(@PathVariable Integer page,
                                @PathVariable Integer limit,
                                @ApiParam("老人姓名") String lrname,@ApiParam("状态")  Integer zhuangtai,@ApiParam("创建时间")  String createtime){
        Page<WcshenqingVo> wcshenqingPage = new Page<>(page,limit);
        //获取到外出申请信息以及外出老人信息
        Page<WcshenqingVo> page1 = wcshenqingService.getPageVo(wcshenqingPage,lrname,zhuangtai,createtime);
        List<WcshenqingVo> records = page1.getRecords();
        for (WcshenqingVo record : records) {
            //查询外出老人的床位号
            String bedNo = record.getBedNo();
            //查询外出老人的房间号
            Integer roomNo = record.getRoomNo();
            //将房间号跟床位号拼接起来
            record.setChuanWeiHao(roomNo+"-"+bedNo);
            //获取到外出开始时间
            Date wctime = record.getWctime();
            //获取到外出结束时间
            Date hftime = record.getHftime();
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            //将外出开始结束时间转换为字符串拼接起来为外出时间
            String format = sdf.format(wctime);
            String format1 = sdf.format(hftime);
            record.setCwDate(format + "~" + format1);
        }
        return Result.ok(page1);
    }


    @ApiOperation("外出申请审批-详情")
    @GetMapping("/getByIdWaiChu/{id}")
    public Result getByIdWaiChu(@PathVariable Integer id){
        //根据id获取外出申请信息
        Wcshenqing wcshenqing = wcshenqingService.getById(id);
        //获取该外出申请的老人信息
        Laoren laoren = laorenService.getById(wcshenqing.getLrId());
        //获取该老人的房间信息
        Fangjian fangjian = fangjianService.getById(laoren.getRoomId());
        //获取该老人的床位信息
        Chuangwei chuangwei = chuangweiService.getById(laoren.getBedId());
        laoren.setChuangWeiBed(fangjian.getRoomNo()+"-"+chuangwei.getBedNo());
        //对获取到的房间进行分割,房间号的第一个值为楼层
        String[] strings = fangjian.getRoomNo().toString().split("");
        String str = "";
        for(int i = 0;i<strings.length;i++){
            str = strings[0];
        }
        laoren.setChuangWeiFangJian(str+"楼"+fangjian.getRoomNo()+"室");
        Map<String,Object> map = new HashMap<>();
        map.put("laoren",laoren);
        map.put("wcshenqing",wcshenqing);
        return Result.ok(map);
    }



    @ApiOperation("查看审批设置护理等级变更审批流")
    @GetMapping("/getByHuLiShenPiLiu")
    public Result getByHuLiShenPiLiu(){
        List<Shenpiliu> list = shenpiliuService.list();
        return Result.ok(list);
    }


    @Resource
    private RepositoryService repositoryService;  //部署流程定义
    @Resource
    private RuntimeService runtimeService;  //创建一个流程实例
    @Resource
    private TaskService taskService; //运行任务
    @Resource
    private HistoryService historyService;  //查看执行的任务

    @ApiOperation("护理变更申请审批部署")
    @GetMapping("/huLiProcess")
    public Result huLiProcess(){
        // 流程部署
        Deployment deployment = repositoryService.createDeployment()
                .addClasspathResource("process/hulidengjibiangeng.bpmn20.xml")
                .addClasspathResource("process/hulidengjibiangeng.png")
                .name("护理等级变更申请流程")
                .deploy();
        System.out.println("流程部署id：" + deployment.getId());
        System.out.println("流程部署名称：" +deployment.getName());
        return Result.ok();
    }

    @ApiOperation("开启护理等级变更流程")
    @GetMapping("/startProcess/{name}/{id}")
    public Result startProcess(@PathVariable("name") String name,@PathVariable("id")String id){
        Map<String,Object> variables = new HashMap<>();
        variables.put("name",name);
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("hulidengjibiangeng",id,variables);
        System.out.println("流程定义id:"+processInstance.getProcessDefinitionId());
        System.out.println("流程实例id"+processInstance.getId());
        System.out.println("当前活动Id"+processInstance.getActivityId());
        return Result.ok();
    }

    /**
    * 查询当前个人待执行的任务
    */
    @ApiOperation("查询当前个人待执行的任务")
    @GetMapping("/findPendingTaskList/{name}")
    public Result findPendingTaskList(@PathVariable("name") String name){
        //任务负责人
        List<Task> list = taskService.createTaskQuery()
                .taskAssignee(name)//只查询该任务负责人的任务
                .list();
        for (Task task : list) {
            System.out.println("流程实例id:"+task.getProcessInstanceId());
            System.out.println("任务id"+task.getId());
            System.out.println("任务负责人:"+task.getAssignee());
            System.out.println("任务名称:"+task.getName());
        }
        return Result.ok();
    }

    /**
     * 完成任务
     */
    @ApiOperation("/完成任务")
    @GetMapping("/compleTask/{name}")
    public Result compleTask(@PathVariable("name") String name){
//        Task task = taskService.createTaskQuery()
//                .taskAssignee(name)//要查询的负责人
//                .singleResult();
        //完成任务,参数:任务id
        //        taskService.complete(task.getId());
        List<Task> taskList = taskService.createTaskQuery()
                .taskAssignee(name)//要查询的负责人
                .list();
        //完成任务,参数:任务id
        for (Task task : taskList) {
            taskService.setVariable(task.getId(),"result",0);
            taskService.complete(task.getId());
        }
        return Result.ok();
    }
    /*图片上传上传图片接口*/
    /*图片上传地址*/
    //String fileSavePath = "D:\\VSCode\\实训\\ylHomes\\vue-ylHomes\\public\\upload\\";
//    String currentDirectory = System.getProperty("user.dir");       //System.getProperty("user.dir")会返回当前工作目录的路径
//    String fileSavePath = "service-ylHouse\\src\\main\\resources\\upload\\";
//    String absolutePath = currentDirectory + "/" + fileSavePath;
    //String fileSavePath = "D:\\VSCode\\实训\\ylHomes\\vue-ylHomes\\public\\upload\\";
    String fileSavePath = "D:\\ylHomes\\ylHomes\\public\\upload\\";
    /*格式化时间*/
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/");
    @PostMapping("/saveUpload")
    @ApiOperation(value = "图片上传")
    @CrossOrigin
    public Result uploadFile (@ApiParam(name = "file", value = "上传", required = true) @RequestPart("file") MultipartFile file, HttpServletRequest request){
        /*将时间转化成字符串*/
        Date date = new Date();
        String directory = simpleDateFormat.format(date);
        /*文件路径是否存在
         * 如果不存在,则创建
         */
        File dir = new File(fileSavePath + directory);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        /*获取图片的名字*/
        String imageName = file.getOriginalFilename();
        System.out.println("图片上传位置" + fileSavePath + directory);
        /*给文件创建一个新的名字*/
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        /*图片新的名字*/
        String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
        System.out.println("上传的图片位置" + fileSavePath + directory + newFileName);
        /*创建新文件*/
        File newFile = new File(fileSavePath + directory + newFileName);
        try {
            file.transferTo(newFile);
            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/images/" + directory + newFileName;
            System.out.println("图片上传成功的url:" + url);
            String sql = "/upload/" + directory + newFileName;
            /*返回给前端的字符串地址,然后添加的时候将这一串字符串加入到数据库中*/
            return Result.ok(sql);
        } catch (IOException e) {
            return Result.ok();
        }
    }


    @ApiOperation(value = "审批通过把该审批人姓名跟最后一个通过的合同存入护理审批表")
    @PostMapping("/saveShenPiHuLi/{id}")
    public Result saveShenPiHuLi(@RequestBody Huligenghuanshenpi huligenghuanshenpi, @PathVariable Long id){
        HuLiDengJiBianGeng byId = huLiDengJiBianGengService.getById(id);
        Long laorenId = byId.getLaorenId();
        huligenghuanshenpi.setCreatime(new Date());
        huligenghuanshenpi.setLaorenId(laorenId);
        huligenghuanshenpiService.save(huligenghuanshenpi);
        return Result.ok();
    }

    @ApiOperation("护理审批通过后修改老人信息")
    @GetMapping("/updateByHuLiId/{id}")
    public Result updateByHuLiId(@PathVariable Long id){
        //根据护理申请id查询该申请信息
        HuLiDengJiBianGeng huLiDengJiBianGengServiceById = huLiDengJiBianGengService.getById(id);
        //将状态改为已通过
        huLiDengJiBianGengServiceById.setState(1);
        huLiDengJiBianGengService.updateById(huLiDengJiBianGengServiceById);
        //获取到该老人外键
        Long laorenId = huLiDengJiBianGengServiceById.getLaorenId();
        //根据老人外键获取到老人信息
        Laoren laoren = laorenService.getById(laorenId);
        //获取到该申请变更的等级
        String nursingGrade = huLiDengJiBianGengServiceById.getNursingGrade();
        //根据等级名称获取到该等级id
        LambdaQueryWrapper<HulidengjiBean> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(HulidengjiBean::getDengji,nursingGrade);
        HulidengjiBean one = hulidengjiService.getOne(lambdaQueryWrapper);
        Long oneId = one.getId();
        //将老人的原等级id改为变更后的等级id
        laoren.setCareLevelId(oneId);
        laorenService.updateById(laoren);
        return Result.ok();
    }


    @ApiOperation("查看审批设置外出申请审批流")
    @GetMapping("/getByWaiChuShenPiLiu")
    public Result getByWaiChuShenPiLiu(){
        List<Shenpiliu> list = shenpiliuService.list();
        return Result.ok(list);
    }
    @ApiOperation("外出申请审批部署")
    @GetMapping("/waiChuProcess")
    public Result waiChuProcess(){
        // 流程部署
        Deployment deployment = repositoryService.createDeployment()
                .addClasspathResource("process/waichushenqing.bpmn20.xml")
                .addClasspathResource("process/waichushenqing.png")
                .name("外出申请审批流程")
                .deploy();
        System.out.println("流程部署id：" + deployment.getId());
        System.out.println("流程部署名称：" +deployment.getName());
        return Result.ok();
    }

    @ApiOperation("开启外出申请审批流程")
    @GetMapping("/startWaiChuProcess/{name}/{id}")
    public Result startWaiChuProcess(@PathVariable("name") String name,@PathVariable("id")String id){
        Map<String,Object> variables = new HashMap<>();
        variables.put("name",name);
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("waichushenqing",id,variables);
        System.out.println("流程定义id:"+processInstance.getProcessDefinitionId());
        System.out.println("流程实例id"+processInstance.getId());
        System.out.println("当前活动Id"+processInstance.getActivityId());
        return Result.ok();
    }


    @ApiOperation(value = "外出申请审批通过把该审批人姓名跟最后一个通过的合同存入外出申请审批表")
    @PostMapping("/saveShenPiWaiChu/{id}")
    public Result saveShenPiWaiChu(@RequestBody Waichushenqingshenpi waichushenqingshenpi, @PathVariable Integer id){
        Wcshenqing wcshenqing = wcshenqingService.getById(id);
        Integer lrId = wcshenqing.getLrId();
        waichushenqingshenpi.setCreateTime(new Date());
        waichushenqingshenpi.setLaorenId(lrId);
        waichushenqingshenpiService.save(waichushenqingshenpi);
        return Result.ok();
    }

    @ApiOperation("外出申请审批通过后修改状态")
    @GetMapping("/updateByWaiChuId/{id}")
    public Result updateByWaiChuId(@PathVariable Long id){
        //根据外出申请id查询该申请信息
        Wcshenqing wcshenqing = wcshenqingService.getById(id);
        //将状态改为已通过
        wcshenqing.setWczhuangtai(2);
        wcshenqingService.updateById(wcshenqing);
        return Result.ok();
    }

    @ApiOperation("护理等级变更审批拒绝")
    @GetMapping("/refuseHuLi/{name}")
    public Result refuseHuLi(@PathVariable("name") String name){
        ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = defaultProcessEngine.getTaskService();
        List<Task> taskList = taskService
                .createTaskQuery()
                .processDefinitionKey("hulidengjibiangeng")
                .taskAssignee(name)
                .list();
        Authentication.setAuthenticatedUserId(name);
        //异常结束
        for (Task task : taskList) {
            taskService.setVariable(task.getId(),"result",1);
            taskService.complete(task.getId());
        }
        return Result.ok();
    }


    @ApiOperation("护理等级变更拒绝时改变状态")
    @GetMapping("/updateByHuLiRefuse/{id}")
    public Result updateByHuLiRefuse(@PathVariable Integer id){
        HuLiDengJiBianGeng huLiDengJiBianGeng = huLiDengJiBianGengService.getById(id);
        huLiDengJiBianGeng.setState(2);
        huLiDengJiBianGengService.updateById(huLiDengJiBianGeng);
        return Result.ok();
    }

    @ApiOperation("护理等级拒绝日志展示")
    @GetMapping("/getByHuLiById/{id}")
    public Result getByHuLiById(@PathVariable Integer id){
        HuLiDengJiBianGeng huLiDengJiBianGeng = huLiDengJiBianGengService.getById(id);
        Long laorenId = huLiDengJiBianGeng.getLaorenId();
        LambdaQueryWrapper<Huligenghuanshenpi> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Huligenghuanshenpi::getLaorenId,laorenId);
        Huligenghuanshenpi huligenghuanshenpi = huligenghuanshenpiService.getOne(lambdaQueryWrapper);
        return Result.ok(huligenghuanshenpi);
    }

    @ApiOperation("外出申请审批拒绝")
    @GetMapping("/refuseWaiChu/{name}")
    public Result refuseWaiChu(@PathVariable String name){
        ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = defaultProcessEngine.getTaskService();
        List<Task> taskList = taskService
                .createTaskQuery()
                .processDefinitionKey("waichushenqing")
                .taskAssignee(name)
                .list();
        Authentication.setAuthenticatedUserId(name);
        //异常结束
        for (Task task : taskList) {
            taskService.setVariable(task.getId(),"result",1);
            taskService.complete(task.getId());
        }
        return Result.ok();
    }

    @ApiOperation("外出申请拒绝时改变状态")
    @GetMapping("/updateByWaiChuRefuse/{id}")
    public Result updateByWaiChuRefuse(@PathVariable Integer id){
        Wcshenqing wcshenqing = wcshenqingService.getById(id);
        wcshenqing.setWczhuangtai(1);
        wcshenqingService.updateById(wcshenqing);
        return Result.ok();
    }


    @ApiOperation("外出申请拒绝日志展示")
    @GetMapping("/getByWaiChuById/{id}")
    public Result getByWaiChuById(@PathVariable Integer id){
        Wcshenqing wcshenqing = wcshenqingService.getById(id);
        Integer lrId = wcshenqing.getLrId();
        LambdaQueryWrapper<Waichushenqingshenpi> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Waichushenqingshenpi::getLaorenId,lrId);
        Waichushenqingshenpi waichushenqingshenpi = waichushenqingshenpiService.getOne(lambdaQueryWrapper);
        return Result.ok(waichushenqingshenpi);
    }
}
